/*
* Copyright (c) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
var serverPath = '//tartan-mafia.appspot.com/';



// The functions triggered by the buttons on the Hangout App
/*
function countButtonClick() {
  // Note that if you click the button several times in succession,
  // if the state update hasn't gone through, it will submit the same
  // delta again.  The hangout data state only remembers the most-recent
  // update.
  console.log('Button clicked.');
  var value = 0;
  var count = gapi.hangout.data.getState()['count'];
  if (count) {
    value = parseInt(count);
  }

  console.log('New count is ' + value);
  // Send update to shared state.
  // NOTE:  Only ever send strings as values in the key-value pairs
  gapi.hangout.data.submitDelta({'count': '' + (value + 1)});
}
*/

var forbiddenCharacters = /[^a-zA-Z!0-9_\- ]/;
function setText(element, text) {
  element.innerHTML = typeof text === 'string' ?
      text.replace(forbiddenCharacters, '') :
      '';
}

function getMessageClick() {
  console.log('Requesting message from main.py');
  var http = new XMLHttpRequest();
  http.open('GET', serverPath);
  http.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var jsonResponse = JSON.parse(http.responseText);
      console.log(jsonResponse);

      var messageElement = document.getElementById('message');
      setText(messageElement, jsonResponse['message']);
    }
  }
  http.send();
}

function stateChanged()
{
	var numStates = 3;
	console.log(gapi.hangout.data.getValue('stateIndex'));
	var stateIndex = JSON.parse(gapi.hangout.data.getValue('stateIndex'));
	switch(stateIndex)
	{
		case 0:
			state_night();
			break;
		case 1:
			state_council();
			break;
		default:
			state_vote();
	}
	gapi.hangout.data.setValue('stateIndex', ((stateIndex + 1) % numStates));
}

function updateStateUi(state) {
  var countElement = document.getElementById('count');
  var stateCount = state['count'];
  if (!stateCount) {
    setText(countElement, 'Probably 0');
  } else {
    setText(countElement, stateCount.toString());
  }
}

function updateParticipantsUi(participants) {
  console.log('Participants count: ' + participants.length);
  var participantsListElement = document.getElementById('participants');
  setText(participantsListElement, participants.length.toString());
}

// A function to be run at app initialization time which registers our callbacks
function init() {
  console.log('Init app.');

  var apiReady = function(eventObj) {
    if (eventObj.isApiReady) {
      console.log('API is ready');
	  console.log("larg");
      gapi.hangout.onApiReady.remove(apiReady);
	  gapi.hangout.data.setValue('setIndex', 0);
	  console.log(gapi.hangout.data.getValue('stateIndex'));
	DesignateRole();
      gapi.hangout.data.onStateChanged.add(function(eventObj) {
        updateStateUi(eventObj.state);
      });
      gapi.hangout.onParticipantsChanged.add(function(eventObj) {
        updateParticipantsUi(eventObj.participants);
      });

      updateStateUi(gapi.hangout.data.getState());
      updateParticipantsUi(gapi.hangout.getParticipants());    }
  };

  // This application is pretty simple, but use this special api ready state
  // event if you would like to any more complex app setup.
  gapi.hangout.onApiReady.add(apiReady);
}


function DesignateRole(){
	console.log('DesignateRole app.');
	var arrayOfParticipants = gapi.hangout.getEnabledParticipants();
	var numOfPeople = arrayOfParticipants.length;
	//mafia of the ID
	var mafiaID = arrayOfParticipants[Math.floor(Math.random()*numOfPeople)].person.id;
	console.log(mafiaID);
	
	gapi.hangout.data.setValue('mafiaID', mafiaID);
	//iterating 
	for(i=0; i<numOfPeople; i++){
		var currPerson = arrayOfParticipants[i].person.id;
		console.log(currPerson);
		if (arrayOfParticipants[i].person.id != mafiaID){
			gapi.hangout.data.setValue(currPerson,'townsperson');
		}
		else{
			gapi.hangout.data.setValue(currPerson, 'mafia');
		}
	}
}


function getVote(){
  var chosen = "";
  var len = document.getElementsByName("killOption").length;
	var pplIndex;
	var role = "";
	console.log("before loop");
    for (i = 0; i <len; i++) {
		console.log("in loop");
      if (document.getElementsByName("killOption")[i].checked) {
	  console.log("in if");
		pplIndex = document.getElementsByName("killOption")[i].value;
		console.log(pplIndex);
		var tList = gapi.hangout.getParticipants();
		console.log(tList);
		chosen = tList[Number(pplIndex)].person.id;
		console.log(chosen);
		role = gapi.hangout.data.getValue(chosen);
	}
    }
	

  if (chosen == "") {
    alert("No Location Chosen");
  }
  else {
    alert("you are "+ role+ "!");
  }
  return false;
}
gadgets.util.registerOnLoadHandler(init);


function state_council(){
	//Get local participant ID
	var personID = gapi.hangout.getParticipantId();
	
	//Get array of participants
	var participantArray = gapi.hangout.getParticipants();
	
	//Check what this person's role is 
	var role = gapi.hangout.data.getValue(personID);
	
	//unmute all but the dead
	if(role == "mafia" || role == "townsperson")
	{
		
		for(i = 0; i < participantArray.length; i++)
		{
			var currId = participantArray[i].person.id;
			//If they're a townsperson, mute them both visually and audibly
			var currRole = gapi.hangout.data.getValue(JSON.stringify(currID));
			if(currRole == "townsperson" || currRole == "mafia")
			{
				gapi.hangout.av.setParticipantVisible(currID,true);
				gapi.hangout.av.setParticipantAudible(currID,true);
			}
		}
	}
}

function state_vote(){}

function state_night()
{
	//Get local participant ID
	var personID = gapi.hangout.getParticipantId();
	
	//Get array of participants
	var participantArray = gapi.hangout.getParticipants();
	
	//Check what this person's role is 
	var role = gapi.hangout.data.getValue(personID);
	
	//If they're the mafia, mute townspeople
	if(role == "mafia")
	{
		
		for(i = 0; i < participantArray.length; i++)
		{
			var currID = participantArray[i].person.id;
			//If they're a townsperson, mute them both visually and audibly
			if(gapi.hangout.data.getValue(currID) == "townsperson")
				gapi.hangout.av.setParticipantAudible(currID,false);
		}
	}
	else if(role == "townsperson")
	{
		for(i = 0; i < participantArray.length; i++)
		{
			var currID = participantArray[i].person.id;
			gapi.hangout.av.setParticipantVisible(currID,false);
			gapi.hangout.av.setParticipantAudible(currID,false);
		}
	}
	
	//Add vote buttons for mafia members here
}


//Kill the local user. He can now only see dead people
function killLocalPerson(deadId)
{
	//Get array of participants
	var participantArray = gapi.hangout.getParticipants();
	
	//Check what this person's role is 
	var role = gapi.Hangout.data.getValue(deadId);
	
	//Declaring participant to be dead
	gapi.hangout.data.setValue(deadId,'dead');
	//gapi.hangout.data.submitDelta({deadId : 'dead'});

/*		
		for(i = 0; i < participantArray.length; i++)
		{
			var currID = participantArray[i].id;
			//If they're a townsperson or mafia, mute them both visually and audibly
			var currRole = gapi.hangout.data.getValue(currID);
			if(currRole == "townsperson" || currRole == "mafia")
			{
				gapi.hangout.av.setParticipantVisible(currID,false);
				gapi.hangout.av.setParticipantAudible(currID,false);
			}
			else //They're dead, so set them alive
			{
				gapi.hangout.av.setParticipantVisible(currID,true);
				gapi.hangout.av.setParticipantAudible(currID,true);
			}
		}
*/		
	//Inform everyone who died. 
		
	
}

//This is a test
function testVisible()
{
	//Get local participant ID
	var localID = gapi.hangout.getParticipantId();
	//Get array of participants
	var participantArray = gapi.hangout.getParticipants();
	for(i =0; i< participantArray.length; i++)
	{
		var currID = participantArray[i].person.id;
		if(true)
		{
			gapi.hangout.av.setParticipantVisible(currID, false);
			gapi.hangout.av.setParticipantAudible(currID, false);
			console.log("in loop");
		}
	}
}